<template>
  <div
    :jiBieArr="[2]"
    :tipArr="[, '数据导入只对站点级别开放', '', , '']"
    style="padding: 15px"
  >
    <el-form
      :model="queryForm"
      ref="queryForm"
      :inline="true"
      label-width="68px"
      style="margin-top: 20px"
      class="globalSerchFormStyle"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input
              v-model="queryForm.phoneNumber"
              placeholder="请输入手机号"
              clearable
              size="small"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="导入状态" prop="importStatus">
            <el-select
              v-model="queryForm.importStatus"
              clearable
              placeholder="请选择"
              size="small"
              style="width: 190px"
            >
              <el-option label="成功" value="0"></el-option>
              <el-option label="失败" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          plain
          >重置</el-button
        >
      </el-col>
      <el-col :span="3.5">
        <!-- <el-button
          plain
          icon="el-icon-edit"
          size="mini"
          @click="batchAdd"
          :loading="importLoading"
          :disabled="importLoading"
          >导入Excel批量新增
          <input
            type="file"
            accept=".xls,.xlsx"
            class="upload_file"
            @change="handleUpload($event)"
            style="display: none"
            id="upload_file"
          />
        </el-button> -->
        <el-button plain icon="el-icon-edit" size="mini" @click="showUpload"
          >批量导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >单条新增</el-button
        >
      </el-col>
    </el-row>

    <!--主要表格-->
    <el-table :data="importList" @selection-change="selectionChange" stripe>
      <!-- <af-table-column
          align="left"
          prop="id"
          type="selection"
          fixed="left"
        /> -->
      <af-table-column
        label="导入状态"
        align="left"
        prop="memberGrade"
        width="160px"
      >
        <template slot-scope="scope">
          {{ scope.row.importStatus == 1 ? "失败" : "成功" }}
        </template>
      </af-table-column>
      <af-table-column
        label="手机"
        align="left"
        prop="phoneNumber"
        fixed="left"
      />
      <af-table-column label="积分" align="left" prop="integral" />
      <af-table-column
        label="电子卡类型"
        align="left"
        prop="memberGrade"
        width="160px"
      >
        <template slot-scope="scope">
          {{ translateCardToName(scope.row) }}
        </template>
      </af-table-column>
      <af-table-column label="电子卡余额(元)" align="left" prop="balance" />
      <af-table-column
        label="成长值"
        align="left"
        prop="growValue"
        width="160px"
      >
        <!-- <template slot-scope="scope">
            {{ translateGradeToName(scope.row) }}
          </template> -->
      </af-table-column>
      <af-table-column label="标签" align="left" prop="labelId" width="160px">
        <template slot-scope="scope">
          {{ translateLabelToName(scope.row) }}
        </template>
      </af-table-column>
      <af-table-column
        label="优惠券导入码"
        align="left"
        prop="couponIssueId"
        width="160px"
      >
      </af-table-column>
      <af-table-column
        label="导入时间"
        align="left"
        prop="createTime"
        width="160px"
      >
      </af-table-column>
      <!-- <af-table-column label="等级操作" align="left">
          <template slot-scope="scope">
            <el-dropdown @command="toGrade">
              <span class="el-dropdown-link" style="font-size: 12px">
                强拉到指定等级<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  :command="scope.row.phoneNumber + '.' + ele.id"
                  v-for="ele in gradeList"
                  :key="ele.id"
                  >{{ ele.grade }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
            <el-popconfirm
              title="将用户强制列为无等级状态，是否继续？"
              confirm-button-text="删除"
              @onConfirm="toUnGrade(scope.row.phoneNumber)"
            >
              <el-button
                type="text"
                icon="el-icon-circle-plus-outline"
                class="underline btn24"
                size="mini"
                slot="reference"
                >拉出等级</el-button
              >
            </el-popconfirm>
          </template>
        </af-table-column>
        <af-table-column
          label="标签"
          align="left"
          prop="labelId"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateLabelToName(scope.row) }}
          </template>
        </af-table-column>
        <af-table-column label="标签操作" align="left">
          <template slot-scope="scope">
            <el-dropdown @command="toLabel">
              <span class="el-dropdown-link" style="font-size: 12px">
                强拉到指定标签<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  :command="scope.row.phoneNumber + '.' + ele.id"
                  v-for="ele in labelList"
                  :key="ele.id"
                  >{{ ele.labelName }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
            <el-popconfirm
              title="将用户强制列为无标签状态，是否继续？"
              confirm-button-text="删除"
              @onConfirm="toUnLabel(scope.row.phoneNumber)"
            >
              <el-button
                type="text"
                icon="el-icon-circle-plus-outline"
                class="underline btn24"
                size="mini"
                slot="reference"
                >拉出标签</el-button
              >
            </el-popconfirm>
          </template>
        </af-table-column>
        <af-table-column
          label="优惠券领取方式"
          align="left"
          prop="couponIssueId"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateIssueToName(scope.row) }}
          </template>
        </af-table-column>
        <af-table-column label="领取方式操作" align="left">
          <template slot-scope="scope">
            <el-dropdown @command="toIssue">
              <span class="el-dropdown-link" style="font-size: 12px">
                强拉到指定领取<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  :command="scope.row.phoneNumber + '.' + ele.id"
                  v-for="ele in issueList"
                  :key="ele.id"
                  >{{ ele.issueRemark }}</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
            <el-popconfirm
              title="将选中用户拉取领取方式，是否继续？"
              confirm-button-text="删除"
              @onConfirm="toUnIssue(scope.row.phoneNumber)"
            >
              <el-button
                type="text"
                icon="el-icon-circle-plus-outline"
                class="underline btn24"
                size="mini"
                slot="reference"
                >拉出领取</el-button
              >
            </el-popconfirm>
          </template>
        </af-table-column> -->
      <!-- <af-table-column label="操作" align="left" width="200px">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              class="underline btn24"
              size="mini"
              @click="upImport(scope.row)"
              >修改</el-button
            >

            <el-popconfirm
              title="确认删除选中的记录？"
              confirm-button-text="删除"
              @onConfirm="delImport(scope.row)"
            >
              <el-button
                type="text"
                icon="el-icon-delete"
                class="underline btn24"
                size="mini"
                slot="reference"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </af-table-column> -->
    </el-table>
    <pagination
      v-show="total > 1"
      :total="total"
      :pageSizes="[10, 50, 100, 200]"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      @pagination="getList"
    />

    <!--拉入前提示框-->
    <el-dialog
      :title="'强拉入' + handleTypeName[handleType]"
      :visible.sync="confirmDialog"
      width="750px"
      append-to-body
    >
      <div class="ml-5">
        无论当前用户此刻是否已经有{{ handleTypeName[handleType] }}，
        点击确认按钮后，会立刻将选中用户拉入新的
        {{ handleTypeName[handleType] }}~
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitLable" size="small"
          >确 定</el-button
        >
        <el-button @click="cancelSubmitLabel" size="small">取 消</el-button>
      </div>
    </el-dialog>
    <!--导入 表格反馈-->
    <el-dialog
      :title="'结果反馈'"
      :visible.sync="tipOpen"
      width="600px"
      append-to-body
      status-icon
      @close="getList"
    >
      <div v-html="tipContent">
        {{ tipContent }}
      </div>
    </el-dialog>

    <!-- 新增单条导入 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      status-icon
      @close="cancel"
    >
      <el-form
        ref="createForm"
        :model="createForm"
        :rules="createFormRules"
        label-width="180px"
      >
        <el-form-item label="手机号" prop="phoneNumber">
          <input
            type="text"
            class="form-control"
            v-model="createForm.phoneNumber"
            style="width: 190px"
          />
        </el-form-item>
        <el-form-item label="油站名称" prop="stationId">
          <el-select
            v-model="createForm.stationId"
            placeholder="请选择油站"
            size="small"
            filterable
            clearable
            style="width: 190px"
          >
            <el-option
              v-for="item in stationList"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="电子卡类型" prop="cardType">
          <el-radio-group v-model="createForm.cardType">
            <div>
              <el-radio label="1">汽油卡</el-radio>
              <el-radio label="2">柴油卡</el-radio>
            </div>
            <div>
              <el-radio label="3">LNG卡</el-radio>
              <el-radio label="4">CNG卡</el-radio>
            </div>
            <div>
              <el-radio label="0">通用卡</el-radio>
            </div>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="电子卡余额" prop="balance">
          <input
            type="text"
            class="form-control"
            v-model="createForm.balance"
            style="width: 190px"
          />
        </el-form-item>

        <el-form-item label="积分余额" prop="integral">
          <input
            type="text"
            class="form-control"
            v-model.number="createForm.integral"
            style="width: 190px"
          />
        </el-form-item>
        <el-form-item label="成长值" prop="growValue">
          <input
            type="text"
            class="form-control"
            v-model.number="createForm.growValue"
            style="width: 190px"
          />
        </el-form-item>

        <!-- <el-form-item label="等级" prop="memberGrade">
          <el-select v-model="createForm.memberGrade" placeholder="请选择">
            <el-option :label="'暂不选择'" :value="''"> </el-option>
            <el-option
              v-for="ele in gradeList"
              :key="ele.id"
              :label="ele.grade"
              :value="ele.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="标签" prop="labelId">
          <el-select v-model="createForm.labelId" placeholder="请选择">
            <el-option :label="'暂不选择'" :value="''"> </el-option>
            <el-option
              v-for="ele in labelList"
              :key="ele.id"
              :label="ele.labelName"
              :value="ele.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券领取方式" prop="couponIssueId">
          <el-select v-model="createForm.couponIssueId" placeholder="请选择">
            <el-option :label="'暂不选择'" :value="''"> </el-option>
            <el-option
              v-for="ele in issueList"
              :key="ele.id"
              :label="ele.issueRemark + ' - ' + ele.issueName"
              :value="ele.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="推送消息" prop="sendFalge">
          <el-radio-group v-model="createForm.sendFalge">
            <div>
              <el-radio :label="0">暂不推送</el-radio>
              <el-radio :label="1">推送消息</el-radio>
            </div>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否替换旧手机号">
          <el-radio-group v-model="createForm.changePhone">
            <div>
              <el-radio :label="false">否</el-radio>
              <el-radio :label="true">是</el-radio>
            </div>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="createForm.changePhone" prop="oldPhoneNumber">
          <el-input
            v-model="createForm.oldPhoneNumber"
            placeholder="请输入旧手机号"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--多条导入的弹窗-->
    <el-dialog
      title="由Excel导入的数据"
      :visible.sync="tempImportDialog"
      append-to-body
      status-icon
      width="80vw"
    >
      <el-table :data="tempImportList" class="mt-5" style="margin-bottom: 10px">
        <af-table-column label="手机" align="left" prop="phoneNumber" />
        <af-table-column
          label="积分"
          align="left"
          prop="integral"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateIntegralToInt(scope.row) }}
          </template>
        </af-table-column>
        <af-table-column
          label="成长值"
          align="left"
          prop="growValue"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateGrowValueToInt(scope.row) }}
          </template>
        </af-table-column>
        <af-table-column
          label="电子卡类型"
          align="left"
          prop="memberGrade"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateCardToName(scope.row) }}
          </template>
        </af-table-column>
        <af-table-column
          label="电子卡余额"
          align="left"
          prop="balance"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateBalanceToFloat(scope.row) }}
          </template>
        </af-table-column>
        <!-- <af-table-column
          label="会员等级"
          align="left"
          prop="memberGrade"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateGradeToName(scope.row) }}
          </template>
        </af-table-column> -->
        <af-table-column label="标签" align="left" prop="labelId" width="160px">
          <template slot-scope="scope">
            {{ translateLabelToName(scope.row) }}
          </template>
        </af-table-column>

        <af-table-column
          label="优惠券领取方式"
          align="left"
          prop="couponIssueId"
          width="160px"
        >
          <template slot-scope="scope">
            {{ translateIssueToName(scope.row) }}
          </template>
        </af-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitExcel">确 定</el-button>
        <el-button @click="cancelExcel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 批量导入 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox
            disabled
            v-model="upload.updateSupport"
          />是否更新已经存在的用户数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate"
            >下载模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="uploadLoading">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import excel from "@/utils/excel";
import {
  getIssueList,
  getGradeList,
  getLabelList,
  importExcel,
  getImportList,
  updateImportList,
  delImportList,
  upImport,
} from "@/api/preData";
import { listIssue } from "@/api/coupon";
import { listEnterpriseStation } from "@/api/dept";
import { getToken } from "@/utils/auth";
import request from "@/utils/request";

export default {
  name: "PreData_DataEntry",
  data() {
    let validateBalance = (rule, value, callback) => {
      let reg = new RegExp("^[0-9]+(\.[0-9]{2})?$");
      if (value === "") {
        callback(new Error("余额不能为空"));
        return;
      }
      if (!reg.test(value)) {
        callback(new Error("请输入最多两位小数的正数"));
        return;
      }
      if (value && value.toString().length >= 11) {
        callback(new Error("长度不能超过11位"));
        return;
      }
      callback();
    };
    let validateLength = (rule, value, callback) => {
      if (value && value.toString().length >= 11) {
        callback(new Error("长度不能超过11位"));
        return;
      }
      callback();
    };
    return {
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        phoneNumber: "",
        importStatus: "",
      },
      tipOpen: false,
      tipContent: "",
      title: "",
      open: false,
      // 总条数
      total: 0,
      importList: [],
      tempImportList: [],
      selectedImport: [],
      confirmDialog: false,
      tempImportDialog: false,
      createForm: {
        phoneNumber: "",
        integral: 0,
        cardType: "1",
        balance: 0,
        memberGrade: "",
        labelId: "",
        couponIssueId: "",
        sendFalge: 0,
        oldPhoneNumber: "",
        changePhone: false, // 是否替换手机号
      },
      issueList: [],
      labelList: [],
      gradeList: [],
      handleTypeName: ["等级", "标签", "优惠券领取方式"],
      handleType: 1, // 0 等级 1 标签 2 优惠券领取方式
      tempId: "",
      tempArr: [],
      importLoading: false,
      dataLoading: false,
      stationList: [],
      dialogUpload: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/customer/cardImport/import",
      },
      upLoadLoading: false,
      createFormRules: {
        stationId: [
          {
            required: true,
            message: "油站不能为空",
            trigger: "blur",
          },
        ],
        balance: [
          { required: true, validator: validateBalance, trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        oldPhoneNumber: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
          { validator: this.validateoldPhoneNumber, trigger: "blur" },
        ],
        growValue: [{ validator: validateLength, trigger: "blur" }],
        integral: [{ validator: validateLength, trigger: "blur" }],
      },
    };
  },
  computed: {},
  created() {
    this.init();
    if (this.$store.state.user.userLevel === "1") {
      this.getStationList(this.presentEnterprise.enterpriseId);
    }
  },
  methods: {
    // 新手机号码校验
    validateoldPhoneNumber(rule, value, callback) {
      if (value === this.createForm.phoneNumber) {
        callback(new Error("新手机号不能与旧手机号相同"));
      } else {
        callback();
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.uploadLoading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.uploadLoading = false
      const tip = `<div style="height:60vh; overflow-y: auto;">${response.msg}</div>`
      this.$alert(tip, "导入结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    async importTemplate() {
      let res = await request.get("/customer/cardImport/template", {
        responseType: "blob",
        withCredentials: false,
      });
      const fileExt = "xlsx";
      const filename = "导入模版" + (fileExt ? "." + fileExt : "");
      const blob = new Blob([res]);
      var downloadElement = document.createElement("a");
      var href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      downloadElement.download = filename;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href);
    },
    showUpload() {
      this.upload.title = "批量导入";
      this.upload.open = true;
    },
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        this.stationList = res;
      });
    },
    init() {
      this.getList();
      this.getIssueList();
      // getIssueList()
      //   .then((res) => {
      //     if (res.code == 200) {
      //       if (res.rows == null) {
      //         this.issueList = [];
      //       } else {
      //         this.issueList = res.rows;
      //       }
      //     } else {
      //       throw new Error("");
      //     }
      //   })
      //   .catch((err) => {
      //     this.msgError("拉取优惠券领取方式失败~");
      //   });
      getLabelList()
        .then((res) => {
          if (res.code == 200) {
            if (res.rows == null) {
              this.labelList = [];
            } else {
              this.labelList = res.rows;
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("拉取标签列表失败~");
        });
      this.cancelSelectFileWatcher();
    },
    cancelSelectFileWatcher() {
      window.onfocus = (e) => {
        (() => {
          setTimeout(() => {
            if (!this.dataLoading) {
              this.importLoading = false;
            }
          }, 500);
        })();
      };
    },
    getIssueList() {
      listIssue({
        // 拉取发放方式
        pageNum: 1,
        pageSize: 1000,
        issueName: null,
        issueRemark: null,
        issueType: "5", // 模板类型
        status: "1", // 状态为启动
      })
        .then((res) => {
          if (res.code == 200) {
            if (res.rows == null) {
              this.issueList = [];
            } else {
              this.issueList = res.rows;
              // console.log("yyyyy", this.issueList);
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("亲，拉取领取方式列表失败~");
        });
    },
    translateIntegralToInt(row) {
      const integral = parseInt(row.integral);
      if (isNaN(integral)) {
        row.integral = 0;
        return 0;
      } else {
        row.integral = integral;
        return integral;
      }
    },
    translateGrowValueToInt(row) {
      const growValue = parseInt(row.growValue);
      if (isNaN(growValue)) {
        row.growValue = 0;
        return 0;
      } else {
        row.growValue = growValue;
        return growValue;
      }
    },
    translateBalanceToFloat(row) {
      const balance = parseFloat(row.balance);
      if (isNaN(balance)) {
        row.balance = 0;
        return 0;
      } else {
        row.balance = balance.toFixed(2);
        return balance.toFixed(2);
      }
    },
    translateIssueToName(row) {
      const id = row.couponIssueId;
      const issue = this.issueList.find((ele) => {
        return ele.id == id;
      });
      if (issue == undefined) {
        row.couponIssueId = undefined;
        return "----";
      }
      return issue.issueRemark + " - " + issue.issueName;
    },
    translateGradeToName(row) {
      const id = row.memberGrade;
      const grade = this.gradeList.find((ele) => {
        return ele.id == id;
      });
      if (grade == undefined) {
        row.memberGrade = undefined;
        return "----";
      }
      return grade.grade;
    },
    translateLabelToName(row) {
      const id = row.labelId;
      const label = this.labelList.find((ele) => {
        return ele.id == id;
      });
      if (!label) {
        row.labelId = undefined;
        return "----";
      }
      return label.labelName;
    },
    translateCardToName(row) {
      const id = row.cardType;
      const typeObj = {
        0: "通用卡",
        1: "汽油卡",
        2: "柴油卡",
        3: "LNG卡",
        4: "CNG卡",
      };

      const type = typeObj[id];
      if (type == undefined) {
        row.cardType = "";
        return "----";
      }
      return type;
    },
    submitForm() {
      this.$refs["createForm"].validate((valid) => {
        if (valid) {
          if (!this.createForm.excelId) {
            this.$confirm("导入的数据会立刻生效，确认导入？", "警告", {
              confirmButtonText: "导入",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              return importExcel([this.createForm])
                .then((res) => {
                  this.open = false;
                  this.tipOpen = true;
                  this.tipContent = res.msg;
                })
                .catch(() => {
                  this.msgError("导入失败，请刷新重试~");
                });
            });
          } else {
            upImport(this.createForm).then((res) => {
              this.open = false;
              this.msgSuccess("修改成功");
            });
          }
        }
      });
    },
    cancel() {
      this.$nextTick(() => {
        this.$refs["createForm"].clearValidate();
      });
      this.open = false;
    },
    batchAdd() {
      this.importLoading = true;
      let upBut = document.getElementById("upload_file");
      upBut.click();
    },
    handleAdd() {
      this.title = "新增数据";
      this.createForm = {
        changePhone: false,
        phoneNumber: "",
        integral: 0,
        cardType: "1",
        balance: 0,
        memberGrade: "",
        labelId: "",
        couponIssueId: "",
        growValue: 0,
        sendFalge: 0,
      };
      this.open = true;
    },
    handleSubmitLable() {
      updateImportList({
        type: this.handleType,
        id: this.tempId,
        phoneArr: this.tempArr,
      })
        .then((r) => {
          this.getList();
          this.confirmDialog = false;
        })
        .catch((e) => {
          this.msgError("操作失败，请刷新后重试~");
        });
    },
    cancelSubmitLabel() {
      this.getList();
      this.confirmDialog = false;
    },
    translationLabel(id) {
      const label = this.labelList.find((ele) => {
        return id == ele.id;
      });
      if (label == undefined) {
        return "";
      }
      return label.labelName;
    },
    toUnGrade(phoneNumber) {
      const delArr = [];
      if (this.selectedImport.length == 0) {
        delArr.push(phoneNumber);
      } else {
        this.selectedImport.map((ele) => {
          if (!!ele.phoneNumber) {
            delArr.push(ele.phoneNumber);
          }
        });
      }
      this.handleType = 0;
      this.tempArr = delArr;
      this.delHandle();
    },
    toUnLabel(phone) {
      const delArr = [];
      if (this.selectedImport.length == 0) {
        delArr.push(phone);
      } else {
        this.selectedImport.map((ele) => {
          if (!!ele.phoneNumber) {
            delArr.push(ele.phoneNumber);
          }
        });
      }
      this.handleType = 1;
      this.tempArr = delArr;
      this.delHandle();
    },
    toUnIssue(phone) {
      const delArr = [];
      if (this.selectedImport.length == 0) {
        delArr.push(phone);
      } else {
        this.selectedImport.map((ele) => {
          if (!!ele.phoneNumber) {
            delArr.push(ele.phoneNumber);
          }
        });
      }
      this.handleType = 2;
      this.tempArr = delArr;
      this.delHandle();
    },
    upImport(row) {
      this.createForm = row;
      this.open = true;
    },
    delImport(row) {
      const delArr = [];
      if (this.selectedImport.length == 0) {
        delArr.push(row.excelId);
      } else {
        this.selectedImport.map((ele) => {
          if (!!ele.excelId) {
            delArr.push(ele.excelId);
          }
        });
      }
      delImportList(delArr)
        .then((res) => {
          this.getList();
          this.msgSuccess("删除成功！");
        })
        .catch((err) => {
          this.msgError("删除失败，请刷新后重试~");
        });
    },
    delHandle() {
      updateImportList({
        type: this.handleType,
        phoneArr: this.tempArr,
      })
        .then((r) => {
          this.getList();
          this.confirmDialog = false;
        })
        .catch((e) => {
          this.msgError("操作失败，请刷新后重试~");
        });
    },
    selectionChange(selection) {
      console.log("selectionChange", selection);

      this.selectedImport = selection;
    },
    getList() {
      getImportList(this.queryForm)
        .then((res) => {
          if (res.rows == null) {
            this.importList = [];
            this.total = 0;
          } else {
            this.importList = res.rows;
            this.total = res.total;
          }
        })
        .catch((err) => {
          this.msgError("拉取导入的数据列表失败");
        });
    },
    submitExcel() {
      this.$confirm("导入的数据会立刻生效，确认导入？", "警告", {
        confirmButtonText: "导入",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        return importExcel(this.tempImportList)
          .then((res) => {
            this.tempImportDialog = false;
            this.tipOpen = true;
            this.tipContent = res.msg;
          })
          .catch(() => {
            this.tempImportDialog = false;
            this.msgError("导入失败，请刷新后重试");
          });
      });
    },
    cancelExcel() {
      this.tempImportDialog = false;
    },
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    toGrade(phoneAndId) {
      const phoneAndIdArr = phoneAndId.match(/\d{1,}/g);
      const phone = phoneAndIdArr[0];
      const id = phoneAndIdArr[1];

      if (!id || !phone) {
        this.msgError("强拉等级失败，刷新重试~");
        return;
      }

      if (this.selectedImport.length == 0) {
        this.tempArr = [phone];
      } else {
        this.tempArr = [];
        this.selectedImport.map((ele) => {
          this.tempArr.push(ele.phoneNumber);
        });
      }

      this.handleType = 0;
      this.tempId = id;

      this.confirmDialog = true;
    },
    toLabel(phoneAndId) {
      const phoneAndIdArr = phoneAndId.match(/\d{1,}/g);
      const phone = phoneAndIdArr[0];
      const id = phoneAndIdArr[1];

      if (!id || !phone) {
        this.msgError("强拉标签失败，刷新重试~");
        return;
      }

      if (this.selectedImport.length == 0) {
        this.tempArr = [phone];
      } else {
        this.tempArr = [];
        this.selectedImport.map((ele) => {
          this.tempArr.push(ele.phoneNumber);
        });
      }

      this.handleType = 1;
      this.tempId = id;

      this.confirmDialog = true;
    },
    toIssue(phoneAndId) {
      const phoneAndIdArr = phoneAndId.match(/\d{1,}/g);
      const phone = phoneAndIdArr[0];
      const id = phoneAndIdArr[1];

      if (!id || !phone) {
        this.msgError("强拉标签失败，刷新重试~");
        return;
      }

      if (this.selectedImport.length == 0) {
        this.tempArr = [phone];
      } else {
        this.tempArr = [];
        this.selectedImport.map((ele) => {
          this.tempArr.push(ele.phoneNumber);
        });
      }

      this.handleType = 2;
      this.tempId = id;

      this.confirmDialog = true;
    },
    handleUpload(e) {
      const files = e.target.files;
      let file = files[0];
      if (!file) {
        document.getElementById("upload_file").value = null;
        this.importLoading = false;
        return;
      }
      const fileExt = file.name.split(".").pop().toLocaleLowerCase();
      if (fileExt === "xlsx" || fileExt === "xls") {
        document.getElementById("upload_file").value = null;
        this.readFile(file);
      } else {
        this.msgError("请选择后缀为.xlsx或者.xls的EXCEL文件");
      }
      this.importLoading = false;
      return false;
    },
    readFile(file) {
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      this.dataLoading = true;
      reader.onloadstart = (e) => {
        console.log("onloadstart");
        this.dataLoading = true;
      };
      reader.onprogress = (e) => {
        console.log("onprogress");
        this.progressPercent = Math.round((e.loaded / e.total) * 100);
      };
      reader.onerror = (e) => {
        this.dataLoaded = false;
        this.importLoading = false;
        this.msgError("文件读取出错");
      };
      reader.onload = (e) => {
        console.log("onload");
        const data = e.target.result;
        const { header, results } = excel.read(data, "array");
        //验证excel导入的有效性
        if (!header.includes("phoneNumber")) {
          this.importLoading = false;
          this.msgError("请使用官方Excel模板导入数据");
          return;
        }
        this.dataLoading = false;
        this.importLoading = false;
        this.tempImportList = results;
        this.tempImportDialog = true;
      };
    },
  },
};
</script>
<style scoped lang="scss">

.app-container {
  .container {
    .row {
      margin-bottom: 10px;
    }
  }
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}

</style>
